package com.cmccsi.utils;

import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis连接池
 * 
 * @author zhangxiaobo
 */
public class RedisConnPool {

	private static final Logger logger = Logger.getLogger(RedisConnPool.class);
	private static JedisPool session_cache_pool = null;

	static {
		try {
			String redis_host = RedisProperties.host;
			int redis_port = Integer.parseInt(RedisProperties.port);

			JedisPoolConfig config = new JedisPoolConfig();
			config.setTestOnBorrow(RedisProperties.testOnBorrow);
			config.setTestOnReturn(RedisProperties.testOnReturn);
			config.setBlockWhenExhausted(RedisProperties.blockWhenExhausted);
			config.setMinIdle(RedisProperties.minIdle);
			config.setMaxIdle(RedisProperties.maxIdle);
			config.setMaxTotal(RedisProperties.maxTotal);
			config.setMaxWaitMillis(RedisProperties.maxWait);

			session_cache_pool = new JedisPool(config, redis_host, redis_port);
		} catch (Throwable e) {
			logger.error(e.getMessage(), e);
		}
	}

	private RedisConnPool() {
	}

	public static Jedis getJedis() {
		return session_cache_pool.getResource();
	}

	/**
	 * return the Jedis object back to JedisPool
	 * 
	 * @param sc
	 *            the Jedis object
	 * @param broken
	 *            if the Jedis object is broken
	 */
	public static void returnJedis(Jedis sc, boolean broken) {
		if (sc != null) {
			try {
				if (broken) {
					session_cache_pool.returnBrokenResource(sc);
				} else {
					session_cache_pool.returnResource(sc);
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				closeJedis(sc);
			}
		}
	}

	private static void closeJedis(Jedis sc) {
		if ((sc != null) && sc.isConnected()) {
			try {
				try {
					sc.quit();
				} catch (Exception e) {
				}
				sc.disconnect();
			} catch (Exception e) {
			}
		}
	}

}
